<template>
  <view class="course-dropdown">
    <view class="dropdown-placeholder"></view>
    <view
      class="dropdown-content"
      :class="{ hidden: dropdownZindex }"
      :style="{ top: globNavbarHeight + globStatusBarHeight - 1 + 'px' }"
    >
      <u-dropdown
        ref="uDropdown"
        :active-color="globPrimaryColor"
        :inactive-color="$u.color['mainColor']"
        height="40px"
        @open="handleDropdownOpen"
        @close="handleDropdownClose"
      >
        <u-dropdown-item
          @change="handleCoursetypeChange"
          v-model="courseTypeValue"
          :title="courseTypeDataTitleText"
          :options="courseTypeData"
        ></u-dropdown-item>

        <u-dropdown-item :title="courseCategoryDataTitleText">
          <view class="category-wrap">
            <scroll-view
              scroll-y
              scroll-with-animation
              class="tab-view menu-scroll-view"
              :scroll-top="scrollTop"
            >
              <view
                class="tab-item"
                :class="[current == 0 ? 'active' : '']"
                @tap.stop="categoryClickLevel(0)"
                ><text>全部</text></view
              >
              <view
                v-for="(item, index) in list"
                :key="index"
                class="tab-item"
                :class="[current == index + 1 ? 'active' : '']"
                @tap.stop="swichMenu(index + 1)"
              >
                <text class="u-line-1">{{ item.title }}</text>
              </view>
            </scroll-view>
            <edu-empty marginTop="0" v-if="current == 0" style="width: 100%"></edu-empty>
            <block v-else>
              <block v-for="(item, index) in list" :key="index">
                <scroll-view scroll-y class="right-box" v-if="current == index + 1">
                  <view class="page-view">
                    <view
                      class="class-title"
                      :class="[categoryId == item.id ? 'active' : '']"
                      @click="categoryClickAll(item)"
                    >
                      <text>全部</text>
                      <u-icon name="arrow-right"></u-icon>
                    </view>
                    <view class="class-item" v-for="(item1, index1) in item.child" :key="index1">
                      <view
                        class="item-title"
                        :class="[categoryId == item1.id ? 'active' : '']"
                        @click="handleCategoryParamClick(item1)"
                      >
                        <text>{{ item1.title }}</text>
                        <u-icon name="arrow-right"></u-icon>
                      </view>

                      <view class="item-container">
                        <view class="thumb" v-for="(item2, index2) in item1.child" :key="index2">
                          <view
                            class="name"
                            :class="[categoryId == item2.id ? 'active' : '']"
                            @click="handleCategoryParamClick(item2)"
                          >
                            {{ item2.title }}</view
                          >
                        </view>
                      </view>
                    </view>
                  </view>
                </scroll-view>
              </block>
            </block>
          </view>
        </u-dropdown-item>
        <u-dropdown-item
          @change="handleCourseOrderChange"
          v-model="courseOrderValue"
          :title="courseOrderDataTitleText"
          :options="courseOrderData"
        ></u-dropdown-item>
        <u-dropdown-item title="筛选">
          <view class="order-content">
            <view class="order-item">
              <view class="title">筛选</view>
              <view class="order-list u-flex u-flex-wrap">
                <view
                  class="item"
                  :class="[screeningParamType == item.value ? 'active' : '']"
                  v-for="(item, index) in screeningParam"
                  :key="index"
                  @click="handleScreeningParamClick(item.value)"
                >
                  {{ item.label }}
                </view>
              </view>
            </view>
            <view class="order-item">
              <view class="title">价格</view>
              <view class="order-list u-flex u-flex-wrap">
                <view
                  class="item"
                  :class="[screeningPriceType == item.value ? 'active' : '']"
                  v-for="(item, index) in screeningPrice"
                  :key="index"
                  @click="handleScreeningPriceClick(item.value)"
                >
                  {{ item.label }}
                </view>
              </view>
            </view>
            <view class="order-item">
              <view class="order-price-input u-flex">
                <u-input
                  v-model="screeningPrice_min"
                  :clearable="false"
                  placeholder="最低价格"
                  maxlength="7"
                  :border="true"
                  input-align="center"
                  height="64"
                />
                <view class="line">
                  <u-line color="#DCDFE6" />
                </view>
                <u-input
                  v-model="screeningPrice_max"
                  :clearable="false"
                  placeholder="最高价格"
                  maxlength="7"
                  :border="true"
                  input-align="center"
                  height="64"
                />
              </view>
            </view>
            <view class="u-flex order-btn">
              <view class="left">
                <button class="btn u-fix-ios-appearance u-border-top" @click="handleScreeningEmpty">
                  清空筛选
                </button>
              </view>
              <view class="right">
                <edu-button type="primary" @click="handleScreeningChange">确定</edu-button>
              </view>
            </view>
          </view>
        </u-dropdown-item>
      </u-dropdown>
    </view>
  </view>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  props: {
    list: Array,
    sortType: {
      type: String,
      default: '',
    },
    screenType: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      courseTypeValue: '',
      courseOrderValue: this.sortType,
      courseTypeDataTitleText: '课程类型',
      courseTypeData: [],
      courseOrderDataTitle: {
        default: '综合排序',
        splendid: '推荐',
        popular: '畅销',
        latest: '最新',
      },
      courseOrderDataTitleText: '排序',
      courseOrderData: [
        {
          label: '综合排序',
          value: 'default',
        },
        {
          label: '推荐',
          value: 'splendid',
        },
        {
          label: '畅销',
          value: 'popular',
        },
        {
          label: '最新',
          value: 'latest',
        },
      ],
      screeningParamType: '',
      screeningParam: [
        {
          label: '免费',
          value: 'free',
        },
        {
          label: '可试听',
          value: 'audition',
        },
        {
          label: 'VIP',
          value: 'vip',
        },
        {
          label: '活动',
          value: 'event',
        },
      ],
      screeningPriceType: '',
      screeningPrice: [
        {
          label: '价格升序',
          value: 'up',
        },
        {
          label: '价格降序',
          value: 'down',
        },
      ],
      screeningPrice_max: '',
      screeningPrice_min: '',
      params: {},
      current: 0,
      scrollTop: 0,
      menuHeight: 0, // 左边菜单的高度
      menuItemHeight: 0, // 左边菜单item的高度
      categoryId: 0,
      dropdownZindex: true,
      courseCategoryDataTitleText: '分类',
    }
  },
  computed: {
    ...mapGetters({
      globPrimaryColor: 'designSetting/getGlobThemeColor',
      globNavbarHeight: 'projectSetting/globNavbarHeight',
      globStatusBarHeight: 'projectSetting/globStatusBarHeight',
    }),
  },
  created() {
    this.getCourseType()
  },
  mounted() {
    if (this.sortType) {
      this.courseOrderDataTitleText = this.courseOrderDataTitle[this.sortType]
    }
    if (this.screenType) {
      this.screeningParamType = this.screenType
    }
  },
  methods: {
    // 课程类型
    getCourseType() {
      this.$edu.api.getUserCourseBaseType().then((res) => {
        const { data } = res
        this.courseTypeData = data.map((item) => {
          return {
            label: item.title,
            value: item.id,
          }
        })
        this.courseTypeData.unshift({
          label: '全部',
          value: 0,
        })
      })
    },
    // 打开
    handleDropdownOpen() {
      this.$refs.uDropdown.highlight()
      this.dropdownZindex = false
    },
    // 关闭
    handleDropdownClose(index) {
      this.$refs.uDropdown.highlight(index)
      this.dropdownZindex = true
    },
    // 点击左边的栏目切换
    async swichMenu(index) {
      if (index == this.current) return
      this.current = index
      // 如果为0，意味着尚未初始化
      if (this.menuHeight == 0 || this.menuItemHeight == 0) {
        await this.getElRect('menu-scroll-view', 'menuHeight')
        await this.getElRect('tab-item', 'menuItemHeight')
      }
      // 将菜单菜单活动item垂直居中
      this.scrollTop = index * this.menuItemHeight + this.menuItemHeight / 2 - this.menuHeight / 2
    },
    // 一级全部按钮
    categoryClickLevel(index) {
      if (index == this.current) return
      this.current = index
      this.$refs.uDropdown.close()
      let category = index
      this.params = {
        ...this.params,
        category,
      }
      this.courseCategoryDataTitleText = '全部'
      this.changeAct()
    },
    // 二级全部按钮
    categoryClickAll(item) {
      this.categoryId = item.id
      this.$refs.uDropdown.close()
      let category = item.id
      this.params = {
        ...this.params,
        category,
      }
      this.courseCategoryDataTitleText = item.title
      this.changeAct()
    },
    // 获取一个目标元素的高度
    getElRect(elClass, dataVal) {
      new Promise((resolve, reject) => {
        const query = uni.createSelectorQuery().in(this)
        query
          .select('.' + elClass)
          .fields(
            {
              size: true,
            },
            (res) => {
              // 如果节点尚未生成，res值为null，循环调用执行
              if (!res) {
                setTimeout(() => {
                  this.getElRect(elClass)
                }, 10)
                return
              }
              this[dataVal] = res.height
            }
          )
          .exec()
      })
    },
    // 课程类型
    handleCoursetypeChange(val) {
      if (this.params.course_type == val) return
      let course_type = val
      this.params = {
        ...this.params,
        course_type,
      }

      const item = this.courseTypeData.find((item) => item.value == val)
      if (item) {
        this.courseTypeDataTitleText = item.label
      }
      this.changeAct()
    },
    // 分类
    handleCategoryParamClick(item) {
      this.categoryId = item.id
      this.$refs.uDropdown.close()
      let category = item.id
      this.params = {
        ...this.params,
        category,
      }
      this.courseCategoryDataTitleText = item.title
      this.changeAct()
    },
    // 排序
    handleCourseOrderChange(val) {
      let order = val
      this.params = {
        ...this.params,
        order,
      }
      this.courseOrderDataTitleText = this.courseOrderDataTitle[val]
      this.changeAct()
    },

    // 筛选初始化分页数据
    changeAct() {
      this.$emit('change', this.delObjectEmpty(this.params))
    },
    // 筛选
    handleScreeningParamClick(val) {
      this.screeningParamType = val
    },
    handleScreeningPriceClick(val) {
      this.screeningPriceType = val
    },
    handleScreeningChange() {
      this.$refs.uDropdown.close()
      // 如果没有选择任何筛选，返回出去
      if (
        this.screeningParamType == '' &&
        this.screeningPriceType == '' &&
        this.screeningPrice_min == '' &&
        this.screeningPrice_max == ''
      )
        return false
      let param = this.screeningParamType
      let price_order = this.screeningPriceType
      let price_min = this.screeningPrice_min
      let price_max = this.screeningPrice_max
      this.params = {
        ...this.params,
        param,
        price_order,
        price_min,
        price_max,
      }
      this.changeAct()
    },
    // 清空筛选
    handleScreeningEmpty() {
      this.$refs.uDropdown.close()
      // 如果没有选择任何筛选，返回出去
      if (
        this.screeningParamType == '' &&
        this.screeningPriceType == '' &&
        this.screeningPrice_min == '' &&
        this.screeningPrice_max == ''
      )
        return false
      this.params.param = ''
      this.screeningParamType = ''
      this.params.price_order = ''
      this.screeningPriceType = ''
      this.params.price_min = ''
      this.screeningPrice_min = ''
      this.params.price_max = ''
      this.screeningPrice_max = ''
      this.changeAct()
    },

    // 去除对象的空值
    delObjectEmpty(data) {
      return Object.keys(data)
        .filter((key) => data[key])
        .reduce((acc, key) => ({ ...acc, [key]: data[key] }), {})
    },
  },
}
</script>

<style lang="scss" scoped>
.course-dropdown {
  width: 100%;
  .dropdown-placeholder {
    height: 80rpx;
  }

  .dropdown-content {
    background-color: #fff;
    position: fixed;
    left: 0;
    right: 0;
    z-index: 997;
    &.hidden {
      overflow: hidden;
    }

    /deep/.u-dropdown__menu__item__text {
      max-width: 120rpx;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
}

.category-wrap {
  display: flex;
  height: calc(100vh - 84px);
  overflow: hidden;
  background-color: #fff;

  .tab-view {
    width: 210rpx;
    height: 100%;
    background: #f7f7f7;

    .tab-item {
      height: 120rpx;
      padding: 0 10rpx;
      background: #f7f7f7;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      color: $edu-content-color;
      font-weight: 400;

      &.active {
        position: relative;
        font-size: 30rpx;
        font-weight: 500;
        color: $edu-main-color;
        background-color: #ffffff;

        &::before {
          content: '';
          position: absolute;
          border-left-width: 6rpx;
          border-left-style: solid;
          @include border-color();
          height: 120rpx;
          left: 0;
          top: 0;
        }
      }
    }
  }

  .page-view {
    padding: 30rpx;
    background-color: #fff;

    .class-title {
      font-size: 30rpx;
      font-weight: 500;
      color: $edu-main-color;
      margin-bottom: 50rpx;

      &.active {
        @include text-color();
      }
    }

    .class-item {
      border-radius: 8rpx;

      .item-title {
        font-size: 30rpx;
        font-weight: 500;
        color: $edu-main-color;
        margin-bottom: 30rpx;

        &.active {
          @include text-color();
        }
      }

      .item-container {
        display: flex;
        flex-wrap: wrap;
        margin-left: -14rpx;
        margin-right: -14rpx;

        .thumb {
          padding: 0 14rpx;
          margin-bottom: 40rpx;
        }

        .name {
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 0 20rpx;
          height: 64rpx;
          background: #f7f7f7;
          border-radius: 32px;
          font-size: 28rpx;
          font-weight: 400;
          color: $u-main-color;

          &.active {
            @include text-color();
          }
        }
      }
    }
  }
}

.order-content {
  background-color: #fff;

  .order-item {
    padding: 20rpx 30rpx;

    .order-list {
      margin-left: -14rpx;
      margin-right: -14rpx;
    }

    .title {
      font-size: 28rpx;
      font-weight: 400;
      color: $edu-tips-color;
      margin-bottom: 16rpx;
    }

    .item {
      width: 180rpx;
      height: 64rpx;
      margin: 12rpx 14rpx;
      font-size: 28rpx;
      font-weight: 400;
      text-align: center;
      color: $edu-content-color;
      line-height: 64rpx;
      background: #f7f7f7;
      border-radius: 32rpx;

      &.active {
        @include text-color();
      }
    }
  }

  .order-price-input {
    margin-bottom: 46rpx;
    width: 502rpx;

    .u-input--border {
      border-radius: 32rpx;
    }

    .line {
      width: 30rpx;
      margin: 0 8rpx;
    }
  }

  .order-btn {
    .left {
      flex: 1;
    }
    .right {
      flex: 1;
    }
    .btn {
      padding: 0;
      font-size: 30rpx;
      color: #606266;
      font-size: 30rpx;
      height: 80rpx;
      line-height: 80rpx;
      background-color: #ffffff;
    }
    ::v-deep button {
      border-radius: 0;
    }
    ::v-deep button:after {
      border-radius: 0;
    }
  }
}
</style>
